package com.loveto.service;

import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;

public class OpenTournamentQuestionActivity extends BaseActivity implements
View.OnClickListener{
	
	// 사용하는 변수들
	private Intent intentMoveToPage;
	private int presentInputRound;
	private JSONArray jsonArrayRecomend;
	private JSONArray jsonArrayLoveharmony;
	private JSONArray jsonArrayLovesituation;
	private JSONArray jsonArrayPresent;
	private LinearLayout areaCategoryList;
	private Handler myHandler = new Handler();
	private ProgressDialog progressDialog; // 프로그레스다이얼로그
	private String presentHighCategory;
	private RelativeLayout btnHighCategory01;
	private RelativeLayout btnHighCategory02;
	private RelativeLayout btnHighCategory03;
	private ImageView btnGotoDirectQuestion;
	private String randomQuestionLowCategory;
	private String randomQuestionText;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_open_tournament_question);
		
		//초기화
		areaCategoryList = (LinearLayout) findViewById(R.id.area_category_list);
		progressDialog = new ProgressDialog(OpenTournamentQuestionActivity.this);
		
		
		//전 엑티비티에서 토너먼트 번호 받아오기
		Intent intent = getIntent();
		presentInputRound = intent.getIntExtra("presentInputRound", 0);
		
		if (isNetworkAvailableAndNotice()) {
			getQuestioinFromServer();
		}
		
		// 클릭 리스너 달기 // 버튼
		btnHighCategory01 = (RelativeLayout) findViewById(R.id.btn_high_category01);
		btnHighCategory01.setOnClickListener(this);
		btnHighCategory02 = (RelativeLayout) findViewById(R.id.btn_high_category02);
		btnHighCategory02.setOnClickListener(this);
		btnHighCategory03 = (RelativeLayout) findViewById(R.id.btn_high_category03);
		btnHighCategory03.setOnClickListener(this);
		btnGotoDirectQuestion = (ImageView) findViewById(R.id.btn_goto_direct_question);
		btnGotoDirectQuestion.setOnClickListener(this);
		RelativeLayout btnGogoBack = (RelativeLayout) findViewById(R.id.btn_goto_back);
		btnGogoBack.setOnClickListener(this);
		
		RelativeLayout randomQuestionBtn = (RelativeLayout) findViewById(R.id.random_question_btn);
		randomQuestionBtn.setOnClickListener(this);
		
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_high_category01:
			if (!("recomend".equals(presentHighCategory))) {
				presentHighCategory = "recomend";
				jsonArrayPresent = jsonArrayRecomend;
				if (isNetworkAvailableAndNotice())
					setQuestionCategory();
			}
			break;
		case R.id.btn_high_category02:
			if (!("loveharmony".equals(presentHighCategory))) {
				presentHighCategory = "loveharmony";
				jsonArrayPresent = jsonArrayLoveharmony;
				if (isNetworkAvailableAndNotice())
					setQuestionCategory();
			}
			break;
		case R.id.btn_high_category03:
			if (!("lovesituation".equals(presentHighCategory))) {
				presentHighCategory = "lovesituation";
				jsonArrayPresent = jsonArrayLovesituation;
				if (isNetworkAvailableAndNotice())
					setQuestionCategory();
			}
			break;
		case R.id.btn_goto_direct_question:
			intentMoveToPage = new Intent(OpenTournamentQuestionActivity.this,OpenTournamentQuestionDirectActivity.class);
			intentMoveToPage.putExtra("presentInputRound", presentInputRound);
			startActivity(intentMoveToPage);
			break;
		case R.id.area_category_low:
			Log.d("tag", "눌렀다!" );
			intentMoveToPage = new Intent(OpenTournamentQuestionActivity.this,OpenTournamentQuestionIndirectDetailActivity.class);
			intentMoveToPage.putExtra("presentInputRound", presentInputRound);
			intentMoveToPage.putExtra("presentHighCategory", presentHighCategory);
			TextView vLowCategory = (TextView) v.findViewById(R.id.category_text_eng);
			String presentLowCategory = vLowCategory.getText().toString();
			intentMoveToPage.putExtra("presentLowCategory", presentLowCategory);
			TextView vLowCategoryNm = (TextView) v.findViewById(R.id.category_text);
			String presentLowCategoryName = vLowCategoryNm.getText().toString();
			intentMoveToPage.putExtra("presentLowCategoryName", presentLowCategoryName);
			startActivity(intentMoveToPage);
			break;
		case R.id.btn_goto_back:
			finish();
			break;
		case R.id.random_question_btn:
			if (isNetworkAvailableAndNotice()) {
				setRandomQuestion();
			}
			
			//이동할 위치 지정
			intentMoveToPage = new Intent(OpenTournamentQuestionActivity.this,OpenTournamentMainActivity.class);
			//토너먼트 정보 내부 DB 저장
			SharedPreferences pref = getSharedPreferences("tournamentMakeInfo", Activity.MODE_PRIVATE);
			Editor editor = pref.edit();
			switch (presentInputRound) {
			case 1:
				editor.putString("lowCategoryNameRound01", randomQuestionLowCategory);
				editor.putString("questionTextRound01", randomQuestionText);
				break;
			case 2:
				editor.putString("lowCategoryNameRound02", randomQuestionLowCategory);
				editor.putString("questionTextRound02", randomQuestionText);
				break;
			case 3:
				editor.putString("lowCategoryNameRound03", randomQuestionLowCategory);
				editor.putString("questionTextRound03", randomQuestionText);
				break;
			}
			editor.commit();
			startActivity(intentMoveToPage);
			break;
		}
	}
	
	private void setRandomQuestion() {
		progressDialog.setMessage("정보를 불러오고 있습니다.");
		progressDialog.show();
		try {
			String jsonText;
			jsonText = JsonUtils
					.getStringFromUrl(LovetoConstant.QUESTION_RANDOM_URL);
			Log.d("tag", jsonText);
			JSONObject getObject = new JSONObject(jsonText);
			randomQuestionLowCategory = getObject
					.getString("question_low_category_nm");
			randomQuestionText = getObject.getString("question_content");
			Log.d("tag", randomQuestionLowCategory);
			Log.d("tag", randomQuestionText);
			Log.d("tag", "");
		} catch (JSONException e) {
			Log.e("tag", "json error : " + e.getMessage());
		} catch (UnsupportedEncodingException e) {
			Log.e("tag", "json error : " + e.getMessage());
		}
		progressDialog.dismiss();
	}
	
	
	private void getQuestioinFromServer() {
		progressDialog.setMessage("정보를 불러오고 있습니다.");
		progressDialog.show();
		new Thread(new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				
				try {
					String jsonText = JsonUtils
							.getStringFromUrl(LovetoConstant.OPEN_TOURNAMENT_QUESTION_URL);
					Log.d("tag", jsonText);
					// 원격에서 읽어온 데이터로 JSON 객체 생성
					try {
						Log.d("tag", "제이슨 출발~");
						JSONObject totalobject = new JSONObject(jsonText);
						jsonArrayRecomend = new JSONArray(totalobject.getString("recomend"));
						jsonArrayLoveharmony = new JSONArray(totalobject.getString("loveharmony"));
						jsonArrayLovesituation = new JSONArray(totalobject.getString("lovesituation"));
						jsonArrayPresent = jsonArrayRecomend;
						presentHighCategory = "recomend";
							
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} finally {
					if (isNetworkAvailableAndNotice()) {
						setQuestionCategory();
					}
					progressDialog.dismiss();
				}

			}
		}).start();
		
	}
	
	
	private void setQuestionCategory() {
		new Thread(new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						areaCategoryList.removeAllViews();
						for (int i=0;i<jsonArrayPresent.length();i++) {
						RelativeLayout qustionLayout = (RelativeLayout) getLayoutInflater()
								.inflate(R.layout.loveto_open_tournament_question_list, null);
						try {
							JSONObject object = jsonArrayPresent.getJSONObject(i);
							TextView categoryText = (TextView) qustionLayout.findViewById(R.id.category_text);
							categoryText.setText(object.getString("question_low_category_nm"));
							TextView categoryTextEng = (TextView) qustionLayout.findViewById(R.id.category_text_eng);
							categoryTextEng.setText(object.getString("question_low_category"));
							RelativeLayout areaQuestionclick = (RelativeLayout) qustionLayout.findViewById(R.id.area_category_low);
							addOnClickListener(areaQuestionclick);
							
							if (i == (jsonArrayPresent.length()-1)) {
								((ImageView)qustionLayout.findViewById(R.id.under_line)).setVisibility(ImageView.INVISIBLE);
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						areaCategoryList.addView(qustionLayout);
						}
						
						if ("recomend".equals(presentHighCategory)) {
							btnHighCategory01.setBackgroundResource(R.drawable.btn_open_tournament_2nd_selected);
							btnHighCategory02.setBackgroundResource(R.drawable.btn_open_tournament_2nd_unselected);
							btnHighCategory03.setBackgroundResource(R.drawable.btn_open_tournament_2nd_unselected);
						} else if ("loveharmony".equals(presentHighCategory)) {
							btnHighCategory01.setBackgroundResource(R.drawable.btn_open_tournament_2nd_unselected);
							btnHighCategory02.setBackgroundResource(R.drawable.btn_open_tournament_2nd_selected);
							btnHighCategory03.setBackgroundResource(R.drawable.btn_open_tournament_2nd_unselected);
						} else if ("lovesituation".equals(presentHighCategory)) {
							btnHighCategory01.setBackgroundResource(R.drawable.btn_open_tournament_2nd_unselected);
							btnHighCategory02.setBackgroundResource(R.drawable.btn_open_tournament_2nd_unselected);
							btnHighCategory03.setBackgroundResource(R.drawable.btn_open_tournament_2nd_selected);
						}
						
					}
				});
			}
		}).start();
		
	}
	
	private void addOnClickListener (RelativeLayout layout) {
		layout.setOnClickListener(this);
	}
	

}
